
const { DomEditor, Boot, SlateElement, IModuleConf } = window.wangEditor
const $ = window.Dom7

//编辑器插件
function withAttachment(editor) {              // JS 语法
  const { Editor, Transforms, Node, Point,Range } = window.Slate
  const { isInline, isVoid, insertBreak, insertText, deleteBackward } = editor
  const newEditor = editor
  newEditor.isInline = elem => {
    const type = DomEditor.getNodeType(elem)
    if (type === 'attachment' || type === 'emoji'||type === 'thumbnail'||type ==='customImage') return true // 针对 type: attachment ，设置为 inline
    if(type === 'title1'||type === 'title2') return false
    return isInline(elem)
  }

  newEditor.isVoid = elem => {
    const type = DomEditor.getNodeType(elem)
    if (type === 'attachment' || type === 'emoji'||type === 'thumbnail'||type ==='customImage') return true // 针对 type: attachment ，设置为 void
    if(type === 'title1'||type === 'title2') return false
    return isVoid(elem)
  }
  newEditor.insertBreak = () => {
    const { selection } = newEditor
    if (selection == null) return insertBreak()

    const [nodeEntry] = Editor.nodes(editor, {
      match: n => {
        return DomEditor.checkNodeType(n, 'blockquote2') || DomEditor.checkNodeType(n, 'title1') || DomEditor.checkNodeType(n, 'title2') || DomEditor.checkNodeType(n, 'title3')
      },
      universal: true,
    })
    if (!nodeEntry) return insertBreak()
    if (nodeEntry[0].type == 'title3' || nodeEntry[0].type == 'title2' || nodeEntry[0].type == 'title1') {
      const node = { type: 'paragraph', children: [{ text: '' }] }
      editor.insertNode(node)
      return 
    }
      const quoteElem = nodeEntry[0]
      const quotePath = DomEditor.findPath(editor, quoteElem)
      const quoteEndLocation = Editor.end(editor, quotePath)

      if (Point.equals(quoteEndLocation, selection.focus)) {
        // 光标位于 blockquote 最后
        const str = Node.string(quoteElem)
        if (str && str.slice(-1) === '\n') {
          // blockquote 文本最后一个是 \n
          editor.deleteBackward('character') // 删除最后一个 \n
          // 则插入一个 paragraph
          // const p = { type: 'paragraph', children: [{ text: '' }] }
          // Transforms.insertNodes(newEditor, p, { mode: 'highest' })
          const node = { type: 'paragraph', children: [{ text: '' }] }
          editor.insertNode(node)
          return
        }
    }
    // 情况情况，插入换行符
    insertText('\n')
  }
  newEditor.deleteBackward = () => {
    return deleteBackward()
  }
  newEditor.deleteForward = () => {
    return deleteForward()
  }
  return newEditor // 返回 newEditor ，重要！！！
}

